﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CNotebook;

namespace NotebookS2.Manufacturing.Transactions
{
    public partial class JobOrder : Form
    {
        public JobOrder()
        {
            InitializeComponent();
        }

        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }

        public DataTable OrderLineItems { get; set; }
        public DataTable MaterialLineItems { get; set; }


        void InitializeSeries()
        {

            string ObjectType = "600";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();


            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtJONumber.Properties.ReadOnly = true;
                txtJONumber.Text = "##########";

            }
            oSeries.Close();



        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "600";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtJONumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();

            cboReceivingWarehouse.Visible = false;
            cboReceivingWarehouse.Properties.DataSource = oTable;
            cboReceivingWarehouse.Properties.DisplayMember = "Dscription";
            cboReceivingWarehouse.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboReceivingWarehouse.Properties.Columns.Add(col);
            cboReceivingWarehouse.Properties.ShowHeader = false;
            cboReceivingWarehouse.Visible = true;
            oManager.Close();
        }

        DataTable GetOrderStructure()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("DocNum", typeof(string));
            dt.Columns.Add("ItemCode", typeof(string));
            dt.Columns.Add("Dscription", typeof(string));
            dt.Columns.Add("QtyOrder", typeof(double));
            dt.Columns.Add("QtyServed", typeof(double));
            dt.Columns.Add("UoM", typeof(string));

            return dt;
        }

        DataTable GetMaterialStructure()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("DocNum", typeof(string));
            dt.Columns.Add("ItemGroup", typeof(string));
            dt.Columns.Add("WhseCode", typeof(string));
            dt.Columns.Add("WhseName", typeof(string));
            dt.Columns.Add("ItemCode", typeof(string));
            dt.Columns.Add("Dscription", typeof(string));
            dt.Columns.Add("BaseQty", typeof(double));
            dt.Columns.Add("QtyRequirement", typeof(double));
            dt.Columns.Add("ActualQty", typeof(double));
            dt.Columns.Add("UnitCost", typeof(double));

            return dt;

        }

        void RemoveBlankLastFirst()
        {
            
            gridViewOrder.MoveLast();
            try
            {
                int iFocusedRowIndex = gridViewOrder.FocusedRowHandle;
                string sItemCode = "";


                sItemCode = gridViewOrder.GetRowCellValue(iFocusedRowIndex, gridViewOrder.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridViewOrder.DeleteRow(iFocusedRowIndex);
                }
            }
            catch { }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void JobOrder_Load(object sender, EventArgs e)
        {
            #region User
            dtDateCreated.EditValue = System.DateTime.Now;
            txtCreatedBy.Text = this.ActiveUserID;
            dtDateModified.EditValue = System.DateTime.Now;
            txtModifiedBy.Text = this.ActiveUserID;
            #endregion

            InitializeSeries();
            cboProductionType.SelectedIndex = 0;

            BindWarehouse();

            dtDateNeeded.Properties.MinValue = System.DateTime.Now;
            dtDateNeeded.EditValue = System.DateTime.Now;

            this.OrderLineItems = GetOrderStructure();
            this.MaterialLineItems = GetMaterialStructure();


            gridControlOrder.DataSource = this.OrderLineItems;
            gridControlOrder.Refresh();

            gridControlMaterials.DataSource = this.MaterialLineItems;
            gridControlMaterials.Refresh();


            if (gridViewOrder.RowCount <= 0)
            {
                gridViewOrder.AddNewRow();
            }

            if (gridViewMaterials.RowCount <= 0)
            {
                gridViewMaterials.AddNewRow();
            }

            

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            RemoveBlankLastFirst();

            SqlConnection oConnection = new SqlConnection();
            SqlCommand oCommand = new SqlCommand();

            txtJONumber.Text = GetNewSeries();

            oConnection.ConnectionString = this.ConnectionString;
            oConnection.Open();

            oCommand.Connection = oConnection;
            oCommand.CommandText = "INSERT INTO OJO (DocNum, ProductionType, DateNeeded, WhseCode, WhseName, Remarks, DocStatus, DateCreated, CreatedBy, DateModified, ModifiedBy) VALUES (@DocNum, @ProductionType, @DateNeeded, @WhseCode, @WhseName, @Remarks, @DocStatus, @DateCreated, @CreatedBy, @DateModified, @ModifiedBy) ";

            oCommand.Parameters.Add(new SqlParameter("@DocNum", txtJONumber.Text));
            oCommand.Parameters.Add(new SqlParameter("@ProductionType", cboProductionType.Text));
            oCommand.Parameters.Add(new SqlParameter("@DateNeeded", Convert.ToDateTime(dtDateNeeded.EditValue)));
            oCommand.Parameters.Add(new SqlParameter("@WhseCode", Convert.ToString(cboReceivingWarehouse.EditValue)));
            oCommand.Parameters.Add(new SqlParameter("@WhseName", Convert.ToString(cboReceivingWarehouse.Text)));
            oCommand.Parameters.Add(new SqlParameter("@Remarks", Convert.ToString(txtRemarks.Text)));
            oCommand.Parameters.Add(new SqlParameter("@DocStatus", Convert.ToString(txtDocStatus.Text)));

            oCommand.Parameters.Add(new SqlParameter("@DateCreated", Convert.ToDateTime(dtDateCreated.EditValue)));
            oCommand.Parameters.Add(new SqlParameter("@CreatedBy", Convert.ToString(txtCreatedBy.Text)));
            oCommand.Parameters.Add(new SqlParameter("@DateModified", Convert.ToDateTime(dtDateModified.EditValue)));
            oCommand.Parameters.Add(new SqlParameter("@ModifiedBy", Convert.ToString(txtModifiedBy.Text)));

            oCommand.ExecuteNonQuery();

            foreach (DataRow oRow in this.OrderLineItems.Rows)
            {
                SqlCommand oLineCommand = new SqlCommand();
                oLineCommand.Connection = oConnection;

                oLineCommand.CommandText = "INSERT INTO JO1 (DocNum, ItemCode, Dscription, QtyOrder, QtyServed, UoM) VALUES (@DocNum, @ItemCode, @Dscription, @QtyOrder, @QtyServed, @UoM)";
                oLineCommand.Parameters.Add(new SqlParameter("@DocNum", txtJONumber.Text));
                oLineCommand.Parameters.Add(new SqlParameter("@ItemCode", oRow["ItemCode"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@Dscription", oRow["Dscription"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@QtyOrder", oRow["QtyOrder"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@QtyServed", oRow["QtyServed"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@UoM", oRow["UoM"].ToString()));

                oLineCommand.ExecuteNonQuery();
              
            }

            foreach (DataRow oRow in this.MaterialLineItems.Rows)
            {
                SqlCommand oLineCommand = new SqlCommand();
                oLineCommand.Connection = oConnection;


                oLineCommand.CommandText = "INSERT INTO JO2 (DocNum, ItemGroup, WhseCode, WHseName, ItemCode, Dscription, BaseQty, QtyRequirement, ActualQty,  UnitCost, UoM) VALUES (@DocNum, @ItemGroup, @WhseCode, @WHseName, @ItemCode, @Dscription, @BaseQty, @QtyRequirement, @ActualQty, @UnitCost, @UoM)";

                oLineCommand.Parameters.Add(new SqlParameter("@DocNum", txtJONumber));
                oLineCommand.Parameters.Add(new SqlParameter("@ItemGroup", oRow["ItemGroup"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@WhseCode", oRow["WhseCode"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@WhseName", oRow["WhseName"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@ItemCode", oRow["ItemCode"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@Dscription", oRow["Dscription"].ToString()));

                oLineCommand.Parameters.Add(new SqlParameter("@BaseQty", oRow["BaseQty"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@QtyRequirement", oRow["QtyRequirement"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@ActualQty", oRow["ActualQty"].ToString()));

                oLineCommand.Parameters.Add(new SqlParameter("@UoM", oRow["UoM"].ToString()));
                oLineCommand.Parameters.Add(new SqlParameter("@UnitCost", oRow["UnitCost"].ToString()));

                oLineCommand.ExecuteNonQuery();
            }

            oConnection.Close();
        }

        private void txtOrderItem_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_ITM_PRD_ONLY oForm = new FND_ITM_PRD_ONLY();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            string sItemCode = oForm.SelectedItemCode;
            string sItemName = oForm.SelectedItemName;
            string sUoM = oForm.SelectedUoM;


            gridViewOrder.SetRowCellValue(gridViewOrder.FocusedRowHandle, gridViewOrder.Columns["ItemCode"], oForm.SelectedItemCode);
            gridViewOrder.SetRowCellValue(gridViewOrder.FocusedRowHandle, gridViewOrder.Columns["Dscription"], oForm.SelectedItemName);
            gridViewOrder.SetRowCellValue(gridViewOrder.FocusedRowHandle, gridViewOrder.Columns["UoM"], oForm.SelectedUoM);
            gridViewOrder.SetRowCellValue(gridViewOrder.FocusedRowHandle, gridViewOrder.Columns["QtyServed"], 0);

            gridViewOrder.FocusedColumn = gridViewOrder.Columns["QtyOrder"];
            gridViewOrder.ShowEditor();
        }

        private void gridViewOrder_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (gridViewOrder.IsLastRow)
                {
                    string sItemCode = "";
                    int iCount = gridViewOrder.FocusedRowHandle;

                    sItemCode = gridViewOrder.GetRowCellValue(iCount, gridViewOrder.Columns["ItemCode"]).ToString();

                    if ((sItemCode != "" && (txtDocStatus.Text == "Draft" || txtDocStatus.Text == "Open")) )
                    {
                        gridViewOrder.AddNewRow();

                        gridViewOrder.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridViewOrder.FocusedColumn = gridViewOrder.VisibleColumns[0];
                        gridViewOrder.ShowEditor();
                    }
                }
            }
        }
    }
}
